#include "./sensor.h"
#include "../device/gpio.h"

namespace driver {

using namespace device;

using PL = PE<15>;
using Q7 = PE<14>;
using CP = PE<13>;

Sensor::Sensor() {

    RCC->AHB1ENR |= RCC_AHB1ENR_GPIOEEN;

    ConfigOutput<PL, CP>();
    ConfigUpInput<Q7>();
    PL::Clr();
    CP::Clr();
}

static void delay() {
    for (volatile uint32_t i = 0; i < 50; i ++);
}

uint8_t Sensor::read_value() {

    rtos::Mutex::Auto l(m_mutex);
    uint8_t val = 0;

    PL::Clr();
    delay();
    PL::Set();
    delay();

    if (Q7::Read()) {
        val ++;
    }
    for (uint8_t i = 0; i < 8; i ++) {
        CP::Set();
        val <<= 1;
        if (Q7::Read()) {
            val ++;
        }
        CP::Clr();
        delay();
    }
    return val;
}


}

